<template>
  <view class="content" style="padding-bottom: 0">
    <!-- #ifndef MP-WEIXIN -->
    <!--  <Hedaer
      title="管理企业"
      subtitle="邀请"
      iconColor="#fff"
      style="background-color:transparent;"
      @on-right="inviteClick"
    /> -->
    <Hedaer
      title="管理企业"
      subtitle=" "
      iconColor="#fff"
      style="background-color: transparent"
    />
    <!-- #endif -->
    <my-tab
      className="administration"
      boxName="manage"
      :tabBars="items"
      :current="tabDefault"
      :scrollHeight="scrollHeight"
      @on-current-tab="onCurrentTab"
      @on-loadmore-tab="onLoadmoreTab"
    >
      <view v-if="tabActive === 0" style="padding-bottom: 50rpx">
        <detailsTop typeClass="none" :list="listData">
          <view class="elasticity-box">
            <view class="btn" @click="goPortrait"> 荣耀画像 </view>
            <view class="btn" @click="proxy.$unity3dGlobal()"> 企业空间 </view>
          </view>
        </detailsTop>
        <view class="box">
          <text class="header-title min">基本情况</text>
          <VcCardBox :list="cardData"></VcCardBox>
          <view class="basic"> {{ businessScope }} </view>
        </view>
        <view class="box" style="margin-top: 30rpx">
          <view class="header-title min"
            ><text>企业介绍</text>
            <text v-if="manage == 1" class="edit" @click="introduceModify">{{
              switchData.introduce ? "编辑" : "保存"
            }}</text>
          </view>
          <uni-easyinput
            type="textarea"
            v-if="!switchData.introduce"
            :maxlength="-1"
            autoHeight
            v-model="enterpriseIntroductory"
            placeholder="请输入企业介绍"
          ></uni-easyinput>
          <view v-else class="introduce">
            {{ enterpriseIntroductory }}
          </view>
        </view>
        <view class="box" style="margin-top: 30rpx">
          <view class="header-title min">
            <text>主营业务</text>
            <text v-if="manage == 1" class="edit" @click="mainBusinessModify">
              {{ switchData.business ? "编辑" : "保存" }}
            </text>
          </view>
          <uni-easyinput
            type="textarea"
            v-if="!switchData.business"
            :maxlength="-1"
            autoHeight
            v-model="mainBusiness"
            placeholder="请输入主营业务"
          />
          <view v-else class="introduce">
            {{ mainBusiness }}
          </view>
        </view>
        <view class="box" style="margin-top: 30rpx">
          <text class="header-title min">企业荣誉</text>
          <tag type-name="green" :label-data="labelData"></tag>
        </view>
        <view class="box" style="margin-top: 30rpx">
          <view class="header-title min"
            ><text>团队介绍</text>
            <text v-if="manage == 1" class="edit" @click="teamIntroductionModify">{{
              switchData.team ? "编辑" : "保存"
            }}</text>
          </view>
          <uni-easyinput
            type="textarea"
            v-if="!switchData.team"
            :maxlength="-1"
            autoHeight
            v-model="teamIntroduction"
            placeholder="请输入团队介绍"
          ></uni-easyinput>
          <view v-else class="introduce">
            {{ teamIntroduction }}
          </view>
        </view>
        <view class="box" style="margin-top: 30rpx">
          <view class="header-title min"
            ><text>企业文化</text
            ><text v-if="manage == 1" class="edit" @click="enterpriseCultureModify">{{
              switchData.culture ? "编辑" : "保存"
            }}</text></view
          >
          <uni-easyinput
            type="textarea"
            v-if="!switchData.culture"
            :maxlength="-1"
            autoHeight
            v-model="enterpriseCulture"
            placeholder="请输入企业文化"
          ></uni-easyinput>
          <view v-else class="introduce">
            {{ enterpriseCulture }}
          </view>
        </view>
      </view>
      <view v-if="tabActive === 1" style="padding-bottom: 50rpx">
        <view class="box" style="min-height: 80vh">
          <none-data v-if="staffData.length == 0" />
          <view class="item_name" v-for="item in staffData" :key="item.id">
            <staffItem :listData="item" @on-click="staffItemClick" :manage="manage" />
          </view>
        </view>
      </view>
      <view v-if="tabActive === 2" style="padding-bottom: 50rpx">
        <view class="box" style="min-height: 80vh">
          <none-data v-if="applicationData.length == 0" />
          <view class="box-btn-group" v-if="applicationData.length > 0">
            <!-- v-if="applicationData.length > 0" -->
            <view class="box-left">
              <up-checkbox
                v-model="checkAll"
                :size="px2Rpx(7)"
                :icon-size="px2Rpx(5)"
                :label="`选中前${maxVlaue}`"
                :labelSize="px2Rpx(8)"
                name="agree"
                @change="checkAllChange"
              />
            </view>
            <view class="box-right">
              <text class="agree-btn" @tap="multiAgree('批量同意')">
                批量同意
              </text>
              <text class="refuse-btn" @tap="multiAgree('批量拒绝')">
                批量拒绝
              </text>
            </view>
          </view>
          <up-checkbox-group v-model="checkAllArray">
            <view
              class="item_name"
              v-for="item in applicationData"
              :key="item.name"
            >
              <up-checkbox 
                :size="px2Rpx(7)"
                :icon-size="px2Rpx(5)" :name="item.id" />
              <staffItem
                :listData="item"
                @on-click="staffItemClick"
                @check-change="header"
              />
            </view>
          </up-checkbox-group>
        </view>
      </view>
    </my-tab>
    <uni-popup popupStyles="z-index: 1003;" ref="alertDialog" type="dialog">
      <view class="alert-dialog">
        <view class="alert-title"> 操作确认 </view>
        <view class="alert-content">
          <view v-if="stateVal == '同意' || stateVal == '拒绝'">
            是否确认<text v-if="stateVal == '同意'" style="color: #00b588"
              >同意</text
            ><text v-if="stateVal == '拒绝'" style="color: #ff7c00">拒绝</text
            >该员工的加入申请？
          </view>
          <view v-else>
            是否确认<text style="color: #fa2000">移除</text>该员工？</view
          >
        </view>
        <view class="alert-btn">
          <view
            class="btn-item alert-cancel"
            @click="proxy.$refs.alertDialog.close()"
            >取消</view
          >
          <view class="btn-item alert-confirm" @click="confirm">确认</view>
        </view>
      </view>
    </uni-popup>
    <uni-popup popupStyles="z-index: 1003;" ref="batch" type="dialog">
      <view class="alert-dialog">
        <view class="alert-title"> 操作确认 </view>
        <view class="alert-content">
          <view>
            是否确认<text v-if="stateVal == '批量同意'" style="color: #00b588"
              >同意</text
            ><text v-if="stateVal == '批量拒绝'" style="color: #ff7c00"
              >拒绝</text
            >选中员工的加入申请？
          </view>
        </view>
        <view class="alert-btn">
          <view class="btn-item alert-cancel" @click="proxy.$refs.batch.close()"
            >取消</view
          >
          <view class="btn-item alert-confirm" @click="confirmBatch">确认</view>
        </view>
      </view>
    </uni-popup>
    <uni-popup popupStyles="z-index: 1003;" ref="popup" background-color="#fff">
      <popupContent
        title="邀请加入公司"
        text="通过分享链接加入公司，加入后需要管理员审核"
        btnText="一键复制邀请链接"
        :enterpriceName="enterpriseName"
        @on-click="getNewComment"
        :imageUrl="imageUrl"
        :list="honorList"
        :time="creatTime"
      ></popupContent>
    </uni-popup>
  </view>
</template>

<script setup>
import { customNav } from "@/utils/customNav";
import { ref, getCurrentInstance, nextTick } from "vue";
import { px2Rpx } from "../../../utils/utils";
import MyTab from "@/components/tabs/index.vue";
import XBox from "@/components/box/index.vue";
import Hedaer from "@/components/header/index.vue";
import detailsTop from "./components/details-top.vue";
import VcCardBox from "./components/card.vue";
import tag from "./components/tag.vue";
import popupContent from "./componments/popup-content.vue";
import staffItem from "./componments/staff.vue";
import {
  generateTokenLink,
  getAppEnterpriseBaseInfo,
  getEnterpriseHonorByEnterprise,
  getEnterpriseEmpPageList,
  removeEnterpriseEmp,
  getUserBindEnterpriseCheckPageList,
  updateCheckStatus,
  updateEnterpriseBaseInfo,
  getUserInfoApi,
} from "@/api/user/index.js";
import { onLoad } from "@dcloudio/uni-app";
import UniEasyinput from "@/uni_modules/uni-easyinput/components/uni-easyinput/uni-easyinput.vue";
import { auditJoinEnterpriseApi } from "@/api/user/enterpriseAbout";
const { proxy } = getCurrentInstance();
const enterpriseId = ref("");
const enterpriseName = ref("");
const checkAll = ref(false);
const checkAllArray = ref([]);
const maxVlaue = ref(100);
const items = ref([
  { id: 0, name: "信息编辑" },
  { id: 1, name: "员工列表" },
  { id: 2, name: "申请列表" },
]);
const creatTime = ref("");
const listData = ref({
  name: "",
  state: "",
  label: [],
  stage: "",
  phone: "",
  address: "",
});
const switchData = ref({
  introduce: true,
  business: true,
  team: true,
  culture: true,
});
const pageSize = ref(10);
const total = ref(0);
// 员工列表
const staffData = ref([]);
// 本人是否是管理员
const manage = ref(null);
// 申请列表
const applicationData = ref([]);
const callData = ref([]);
const cardData = ref([]);
// 企业经营范围
const businessScope = ref("");
// 企业介绍
const enterpriseIntroductory = ref("");
// 企业文化
const enterpriseCulture = ref("");
// 主营业务
const mainBusiness = ref("");
// 团队介绍
const teamIntroduction = ref("");
const labelData = ref([]);
const tabDefault = ref(0);
const tabActive = ref(0);
const stateVal = ref("");
const scrollHeight = ref(0);
// 获取企业数据
async function getAppEnterpriseBaseInfoData() {
  const res = await getUserInfoApi()
  manage.value = res.data.enterpriseManger;
  getAppEnterpriseBaseInfo(enterpriseId.value).then((res) => {
    listData.value = {
      name: res.data.enterpriseName,
      state: res.data.registerStatus,
      label: ["小微企业", "高新技术", "市级专精特新"],
      stage: res.data.scCode,
      phone: res.data.phone,
      address: res.data.address,
    };
    cardData.value = [
      {
        label: "法定代表人",
        value: res.data.legalRepresentative,
        type: "name",
        unit: "",
      },
      {
        label: "注册资本",
        value: res.data.capital,
        type: "num",
      },
      {
        label: "成立日期",
        value: res.data.establishTime,
        type: "data",
        unit: "",
      },
      {
        label: "企业规模",
        value: res.data.enterpriseScale,
        type: "name",
        unit: "",
      },
      {
        label: "行业类型",
        value: res.data.industryBigType,
        type: "name",
        unit: "",
      },
      {
        label: "所属区县",
        value: res.data.counties,
        type: "num",
      },
    ];
    creatTime.value = res.data.establishTime;
    businessScope.value = res.data.businessScope;
    enterpriseIntroductory.value = res.data.enterpriseIntroductory;
    mainBusiness.value = res.data.mainBusiness;
    teamIntroduction.value = res.data.teamIntroduction;
    enterpriseCulture.value = res.data.enterpriseCulture;
  });
  getEnterpriseHonorByEnterprise(enterpriseId.value).then((res) => {
    labelData.value = res.data.map((o) => {
      return o.enterpriseHonor;
    });
  });
}
// 企业介绍修改
const  introduceModify = () => {
  console.log("ssssssss");
  if (switchData.value.introduce) {
    switchData.value.introduce = !switchData.value.introduce;
  } else {
    let data = {
      id: enterpriseId.value,
      enterpriseIntroductory: enterpriseIntroductory.value,
    };
    updateExecute(data).then((res) => {
      if (res.code == 200) {
        switchData.value.introduce = !switchData.value.introduce;
        uni.showToast({
          title: "修改成功",
        });
        getAppEnterpriseBaseInfoData();
      }
    });
  }
}
// 主营业务修改
function mainBusinessModify() {
  if (switchData.value.business) {
    switchData.value.business = !switchData.value.business;
  } else {
    let data = {
      id: enterpriseId.value,
      mainBusiness: mainBusiness.value,
    };
    updateExecute(data).then((res) => {
      if (res.code == 200) {
        switchData.value.business = !switchData.value.business;
        uni.showToast({
          title: "修改成功",
        });
        getAppEnterpriseBaseInfoData();
      }
    });
  }
}
// 团队介绍修改
function teamIntroductionModify() {
  if (switchData.value.team) {
    switchData.value.team = !switchData.value.team;
  } else {
    let data = {
      id: enterpriseId.value,
      teamIntroduction: teamIntroduction.value,
    };
    updateExecute(data).then((res) => {
      if (res.code == 200) {
        switchData.value.team = !switchData.value.team;
        uni.showToast({
          title: "修改成功",
        });
        getAppEnterpriseBaseInfoData();
      }
    });
  }
}
// 企业文化修改
function enterpriseCultureModify() {
  if (switchData.value.culture) {
    switchData.value.culture = !switchData.value.culture;
  } else {
    let data = {
      id: enterpriseId.value,
      enterpriseCulture: enterpriseCulture.value,
    };
    updateExecute(data).then((res) => {
      if (res.code == 200) {
        switchData.value.culture = !switchData.value.culture;
        uni.showToast({
          title: "修改成功",
        });
      }
    });
  }
}
// 修改请求
async function updateExecute(data) {
  let res = await updateEnterpriseBaseInfo(data);
  return res;
}
// 获取企业员工列表
async function getEnterpriseEmpPageListData() {
  let data = {
    enterpriseId: enterpriseId.value,
    limit: pageSize.value,
    page: 1,
  };
  
  
  getEnterpriseEmpPageList(data).then((res) => {
    console.log(res);
    staffData.value = res.data.records.map((o) => {
      return {
        url: o.avatar,
        name: o.realName,
        manage: o.isManager == "1" ? true : false,
        remove: o.isManager == "1" ? false : true,
        position: o.majorName,
        state: o.checkStatus,
        userId: o.userId,
      };
    });

    total.value = res.data.total;
  });
}

// 申请列表
function getUserBindEnterpriseCheckPageListData() {
  let data = {
    enterpriseId: enterpriseId.value,
    limit: pageSize.value,
    page: 1,
  };
  getUserBindEnterpriseCheckPageList(data).then((res) => {
    console.log(res);
    applicationData.value = res.data.records.map((o) => {
      return {
        url: o.avatar,
        name: o.userName,
        manage: false,
        remove: false,
        position: o.majorName,
        state: o.checkStatus,
        userId: o.userId,
        enterpriseId: o.enterpriseId,
        id: o.id,
        showCheckbox: true,
        checked: false,
      };
    });
    total.value = res.data.total;
  });
}
const multiAgree = (name) => {
  console.log(applicationData.value);
  stateVal.value = name;
  if (checkAllArray.value.length !== 0) {
    proxy.$refs.batch.open();
  } else {
    uni.showToast({
      title: "请先勾选员工列表",
      duration: 2000,
    });
  }
};
// 标签切换
function onCurrentTab(data) {
  console.log(data);
  tabActive.value = data;
  switch (data) {
    case 0:
      if (enterpriseId.value !=="") {
        getAppEnterpriseBaseInfoData();
      }
      break;
    case 1:
      getEnterpriseEmpPageListData();
      break;
    case 2:
      getUserBindEnterpriseCheckPageListData();
      break;

    default:
      break;
  }
}
// 触底加载
function onLoadmoreTab(data) {
  console.log(data);
  switch (data) {
    case 1:
      if (pageSize.value >= total.value) {
        uni.showToast({
          title: "没有更多数据了",
        });
      } else {
        pageSize.value += 10;
        setTimeout(() => {
          uni.hideLoading();
          getEnterpriseEmpPageListData();
        }, 500);
        uni.showLoading({
          title: "加载中...",
        });
      }
      break;

    default:
      break;
  }
}
function goPortrait() {
  customNav(
    `/package_honour/pages/honour/enterprise-honor-detail?name=${listData.value.name}&&typeName=企业&&id=${enterpriseId.value}`
  );
  
}
// 组件点击事件
function staffItemClick(name, data) {
  console.log(name, data);
  stateVal.value = name;
  proxy.$refs.alertDialog.open();
  callData.value = data;
}

const auditUserJoinEnterPrise = async (staffList) => {
  const params = {
    appUserCheckList: staffList,
  };
  const res = await auditJoinEnterpriseApi(params);
  const { code, data } = res;
  if (code === 200) {
    getUserBindEnterpriseCheckPageListData();
    await uni.showToast({
      title: "审批成功",
      duration: 2000,
    });
    proxy.$refs.batch.close();
    checkAll.value = false;
    getUserBindEnterpriseCheckPageListData();
  }
};
function confirm() {
  console.log(stateVal.value, callData.value);
  let data = [];
  switch (stateVal.value) {
    case "同意":
      data = {
        appUserCheckList: [
          {
            id: callData.value.id,
            checkStatus: 1,
            userId: callData.value.userId,
            realName: callData.value.name,
            enterpriseId: callData.value.enterpriseId,
          },
        ],
      };
      setUserBindEnterpriseCheckPage(data);
      break;
    case "拒绝":
      data = {
        appUserCheckList: [
          {
            id: callData.value.id,
            checkStatus: 2,
            userId: callData.value.userId,
            realName: callData.value.name,
            enterpriseId: callData.value.enterpriseId,
          },
        ],
      };
      setUserBindEnterpriseCheckPage(data);
      break;
    case "移除":
      removeEnterpriseEmp(callData.value.userId).then((res) => {
        console.log(res);
        if (res.code === 200) {
          uni.showToast({
            title: "移除成功",
          });
          proxy.$refs.alertDialog.close();
          setTimeout(() => {
            getEnterpriseEmpPageListData();
          }, 100);
        }
      });
      break;

    default:
      break;
  }
}
function setUserBindEnterpriseCheckPage(data) {
  updateCheckStatus(data).then((res) => {
    console.log(res);
    if (res.code == 200) {
      proxy.$refs.alertDialog.close();
      getUserBindEnterpriseCheckPageListData();
    }
  });
}
function inviteClick() {
  proxy.$refs.popup.open("bottom");
}
function getNewComment() {
  let clip =
    import.meta.env.VITE_SHARE_URL +
    `?name=${enterpriseName.value}&enterpriseId=${enterpriseId.value}`;
  uni.setClipboardData({
    data: clip,
    showToast: false,
    success: function () {
      console.log("success");
      proxy.modal.msg("已复制，快去粘贴吧~");
      proxy.$refs.popup.close("bottom");
    },
  });
  return generateTokenLink(0)
    .then((res) => {
      console.log(res);
    })
    .catch((err) => {
      uni.showTaost({
        title: err.data.msg,
        icon: "none",
      });
    });
}
function checkAllChange(data) {
  if (data) {
    for (let i = 0; i < applicationData.value.length; i++) {
      if (i <= maxVlaue.value) {
        checkAllArray.value.push(applicationData.value[i].id);
      }
    }
  } else {
    checkAllArray.value = [];
  }
}

function confirmBatch() {
  const allAgreeData = checkAllArray.value.map((o) => {
    let pitch = applicationData.value.find((i) => i.id == o);
    return {
      checkStatus: stateVal.value == "批量同意" ? "1" : "2",
      enterpriseId: pitch.enterpriseId,
      id: pitch.id,
      userId: pitch.userId,
    };
  });
  console.log("allAgreeData", allAgreeData);
  auditUserJoinEnterPrise(allAgreeData);
}
function header(data) {
  console.log(data);
}
onLoad((option) => {
  enterpriseId.value = option.enterpriseId;
  enterpriseName.value = option.name;
  getAppEnterpriseBaseInfoData();
  uni.getSystemInfo({
    success: (res) => {
      console.log(res.windowHeight);
      scrollHeight.value = res.windowHeight + "px";
    },
  });
});
</script>

<style lang="less" scoped>
@import url("@/static/style/global.less");

.elasticity-box {
  display: flex;
  flex-flow: row nowrap;
  margin-top: 15rpx;
  justify-content: flex-start;
  height: 60rpx;

  .btn {
    width: 150rpx;
    height: 52rpx;
    background: @bg-color;
    text-align: center;
    line-height: 52rpx;
    margin-right: 20rpx;
    padding: 0 20rpx;
  }
}

.box {
  .box-btn-group {
    display: flex;
    justify-content: space-between;
    align-items: center;
    margin-bottom: 30rpx;
    .box-left {
      display: flex;
      flex-flow: row nowrap;
      align-items: center;
    }
    .agree-btn {
      color: @color-green-text;
      margin-right: 40rpx;
    }
    .refuse-btn {
      color: @color-light-orange-text;
    }
  }
  .item_name {
    display: flex;
    flex-flow: row nowrap;
    justify-content: flex-start;
    align-items: center;
    border-bottom: 1rpx solid #dadada;
    margin-bottom: 50rpx;
    padding-bottom: 20rpx;
  }
  .basic {
    font-family: "ali";
    font-weight: 400;
    font-size: @font-size-23;
    color: @color-black;
  }

  .introduce {
    font-family: "ali";
    font-weight: 400;
    font-size: @font-size-23;
    color: @color-label;
  }

  .elasticity-box {
    display: flex;
    flex-flow: row nowrap;
    margin-top: 15rpx;
    justify-content: flex-start;
    height: 60rpx;

    .btn {
      width: 120rpx;
      height: 52rpx;
      background: @bg-color;
      text-align: center;
      line-height: 52rpx;
      margin-right: 20rpx;
      padding: 0 20rpx;
    }
  }

  .header-title {
    width: 90vw;
    display: flex;
    flex-flow: row nowrap;
    justify-content: flex-start;
    align-items: center;

    .edit {
      color: #5590f6;
      font-weight: 500;
      font-family: "ali-m";
    }
  }
}

.alert-dialog {
  width: 613rpx;
  height: 287rpx;
  border-radius: 15rpx;
  background: @bg-color;

  .alert-title {
    height: 80rpx;
    line-height: 80rpx;
    text-align: center;
    font-size: @font-size-39;
    font-family: "ali";
    font-weight: 400;
    color: @color-black;
  }

  .alert-content {
    padding: 50rpx 20rpx;
    font-family: "ali";
    font-weight: 400;
    font-size: @font-size-23;
    color: @color-black;
  }

  .alert-btn {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;

    .btn-item {
      width: 305rpx;
      text-align: center;
      font-family: "ali";
      font-weight: 400;
      font-size: @font-size-31;
      color: @color-black;

      &.alert-confirm {
        color: @color-blue;
      }
    }
  }
}
</style>
